package com.daybook.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.daybook.pojo.Books;
import com.daybook.pojo.BooksAndCategory;
import com.daybook.service.BooksService;
import com.daybook.util.PageHelp;

@Controller
@RequestMapping(value="/booksMsg")
public class BooksController {
	@Autowired
	private BooksService booksService;
	
	/*********************用户模块*********************************/
	//1.查询上架新书
	@RequestMapping(value = "/getNewBooks", method = RequestMethod.POST)
	public void getNewBooks(HttpServletRequest request, HttpServletResponse response)
			throws IOException, JSONException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 获得新书数量
		String num = request.getParameter("num");
		int count = Integer.valueOf(num);
		//int count = 5;
		List<Books> newBookList=booksService.getBooksByNewTime(count);
		int result=-1;
		if(newBookList!=null){
			result=newBookList.size();
		}
		PrintWriter out = response.getWriter();
		JSONObject obj = new JSONObject();
		obj.put("res", result);
		obj.put("list", newBookList);
		out.print(obj);
	}
	//2.查询畅销书籍
		@RequestMapping(value = "/getBestSellBooks", method = RequestMethod.POST)
		public void getBestSellBooks(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			// 获得新书数量
			String num = request.getParameter("num");
			int count = Integer.valueOf(num);
			//int count = 5;
			List<Books> sellBookList=booksService.getBooksByNewSaleNum(count);
			int result=-1;
			if(sellBookList!=null){
				result=sellBookList.size();
			}
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("res", result);
			obj.put("list", sellBookList);
			out.print(obj);
		}
		//3.首页按类别名查询
				@RequestMapping(value = "/getBookByType", method = RequestMethod.POST)
				public void getBookByType(HttpServletRequest request, HttpServletResponse response)
						throws IOException, JSONException {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=utf-8");
					// 获得新书数量
					String cname = request.getParameter("cname");
					
					//int count = 5;
					List<Books> cnameBookList=booksService.getBooksByCname(cname);
					int result=-1;
					if(cnameBookList!=null){
						result=cnameBookList.size();
					}
					PrintWriter out = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("res", result);
					obj.put("list", cnameBookList);
					out.print(obj);
				}
				// 4.条件查询获取书籍列表
				@RequestMapping(value = "/getBooksListByCondition", method = RequestMethod.POST)
				public void getBooksListByCondition(HttpServletRequest request, HttpServletResponse response)
						throws IOException, JSONException {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=utf-8");
					// 获得页码
					String num = request.getParameter("num");
					Integer pageNow=null;
					if(num!=null&&!num.equals("")){
					 pageNow = Integer.valueOf(num);
					}
					//多种条件查询
					String key=request.getParameter("key");
					String beginDate=request.getParameter("beginDate");
					String endDate=request.getParameter("endDate");
					String beginPrice=request.getParameter("beginPrice");
					String endPrice=request.getParameter("endPrice");
					String typeid=request.getParameter("cid");
					Map<String, Object> map=new HashMap<>();
					if(key!=null&&!key.equals("")){
						map.put("key", key);
					}
					if(beginDate!=null&&!beginDate.equals("")){
						map.put("beginDate", beginDate);
					}
					if(endDate!=null&&!endDate.equals("")){
						map.put("endDate", endDate);
					}
					if(beginPrice!=null&&!beginPrice.equals("")){
						map.put("beginPrice", beginPrice);
					}
					if(endPrice!=null&&!endPrice.equals("")){
						map.put("endPrice", endPrice);
					}
					if(typeid!=null&&!typeid.equals("")){
						int cid=Integer.valueOf(typeid);
						if(cid>0){
							map.put("cid", cid);
						}
					}
					PageHelp page =booksService.getBooksByCondition(map, pageNow);
					// 获取总页数
					int totlpage = page.getTotalPageCount();
					// 强制类型转换
					List<Books> bookList = (List<Books>) page.getList();
					PrintWriter out = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("res", 1);
					obj.put("totalPage", totlpage);
					obj.put("num", bookList.size());
					obj.put("list", bookList);
					out.print(obj);
				}
			//5.查询单本书籍
				@RequestMapping(value = "/getOneBookById", method = RequestMethod.POST)
				public void getOneBookById(HttpServletRequest request, HttpServletResponse response)
						throws IOException, JSONException {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=utf-8");
					// 获得书籍id
					String id = request.getParameter("bid");
					int bid=Integer.valueOf(id);
					BooksAndCategory bookList=booksService.getBookByBid(bid);
					int result=-1;
					if(bookList!=null){
						result=1;
					}
					List<BooksAndCategory> list=new ArrayList();
					list.add(bookList);
					PrintWriter out = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("res", result);
					obj.put("list", list);
					out.print(obj);
					out.close();
				}
	/*********************管理员模块*********************************/
	// 条件查询获取书籍列表
		@RequestMapping(value = "/getBooksList", method = RequestMethod.POST)
		public void getBooksList(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			// 获得页码
			String num = request.getParameter("num");
			int pageNow = Integer.valueOf(num);
			//多种条件查询
			String bkey=request.getParameter("bkey");
			String beginPrice=request.getParameter("beginPrice");
			String bpress=request.getParameter("bpress");
			String bflag=request.getParameter("bflag");
			String typeid=request.getParameter("cid");
			Map<String, Object> map=new HashMap<>();
			if(bkey!=null&&!bkey.equals("")){
				map.put("bkey", bkey);
			}
			if(beginPrice!=null&&!beginPrice.equals("")){
				map.put("beginPrice", beginPrice);
			}
			if(bpress!=null&&!bpress.equals("")){
				map.put("bpress", bpress);
			}
			if(bflag!=null&&!bflag.equals("")&&!bflag.equals("-1")){
				int flag=Integer.valueOf(bflag);
				map.put("bflag", flag);
			}
			if(typeid!=null&&!typeid.equals("")&&!typeid.equals("-1")){
				int cid=Integer.valueOf(typeid);
				map.put("cid", cid);
			}
			PageHelp page =booksService.getBooksPageList(map,pageNow);
			// 获取总页数
			int totlpage = page.getTotalPageCount();
			// 强制类型转换
			List<BooksAndCategory> bookList = (List<BooksAndCategory>) page.getList();
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("res", 1);
			obj.put("totalPage", totlpage);
			obj.put("num", bookList.size());
			obj.put("list", bookList);
			out.print(obj);
		}
		//修改书籍信息
		@RequestMapping(value = "/changeBookInfo", method = RequestMethod.POST)
		public void changeBookInfo(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException, Exception {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			// 获得修改信息
			Books book=new Books();
			String b_id = request.getParameter("bid");
			int bid = Integer.valueOf(b_id);
			book.setBid(bid);
			String bname = request.getParameter("bname");
			book.setBname(bname);
			String bauthor = request.getParameter("bauthor");
			book.setBauthor(bauthor);
			String t_id = request.getParameter("tid");
			int tid = Integer.valueOf(t_id);
			book.setCid(tid);
			String b_flag = request.getParameter("bflag");
			int bflag = Integer.valueOf(b_flag);
			book.setBflag(bflag);
			String bpress = request.getParameter("bpress");
			book.setBpress(bpress);
			String b_pressdate = request.getParameter("bpressdate");
			SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        	Date bpressdate = dateFormat.parse(b_pressdate);
        	book.setBpressdate(bpressdate);
			String b_oprice = request.getParameter("boprice");
			double boprice=Double.valueOf(b_oprice);
			book.setBorgprice(boprice);
			String b_price = request.getParameter("bprice");
			double bprice=Double.valueOf(b_price);
			book.setBprice(bprice);
			String b_number = request.getParameter("bnumber");
			int bnumber=Integer.valueOf(b_number);
			book.setBnumber(bnumber);
			String bdesc = request.getParameter("bdesc");
			book.setBdesc(bdesc);
			int result=-1;
			result=booksService.changeBookInfo(book);
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("res", result);
			out.print(obj);
		}
		//修改书籍状态
		@RequestMapping(value = "/changeBookState", method = RequestMethod.POST)
		public void changeBookState(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException, Exception {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			// 获得修改信息
		
			String b_id = request.getParameter("bid");
			int bid = Integer.valueOf(b_id);
			String b_flag = request.getParameter("bflag");
			int bflag = Integer.valueOf(b_flag);
			int result=-1;
			result=booksService.changeBookState(bid, bflag);
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			obj.put("res", result);
			out.print(obj);
		}
		// 编号验证
		@RequestMapping(value = "/bnumYZ", method = RequestMethod.POST)
		public void getOldBook(HttpServletRequest request, HttpServletResponse response)
				throws IOException, JSONException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			String bnum = request.getParameter("bnum");
			int result = -1;
			result = booksService.getBnum(bnum);
			PrintWriter out = response.getWriter();
			JSONObject obj = new JSONObject();
			// 编号不存在，可以添加
			if (result == 0) {
				obj.put("valid", true);
			} else {
				obj.put("valid", false);
			}
			out.print(obj);
			out.flush();
			out.close();
		}
		//统计
				@RequestMapping(value = "/getTopBooks", method = RequestMethod.POST)
				public void getTopBooks(HttpServletRequest request, HttpServletResponse response)
						throws IOException, JSONException {
					request.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=utf-8");
				
					List<Books> sellBookList=booksService.getTop9Books();
					int result=-1;
					if(sellBookList!=null){
						result=sellBookList.size();
					}
					PrintWriter out = response.getWriter();
					JSONObject obj = new JSONObject();
					obj.put("res", result);
					obj.put("list", sellBookList);
					out.print(obj);
				}
	//添加新书
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public void add(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException, JSONException{
		
		PrintWriter outSu = response.getWriter();
		JSONObject obj = new JSONObject();
		 int result=0;
		 String savePath = request.getServletContext().getRealPath("/upload/");
	        //上传时生成的临时文件保存目录
	        String tempPath = request.getServletContext().getRealPath("/temp");
	        File tmpFile = new File(tempPath);
	        if (!tmpFile.exists()) {
	            //创建临时目录
	            tmpFile.mkdir();
	        }
	        File tmpFile2 = new File(savePath);
	        if (!tmpFile2.exists()) {
	            //创建存储目录
	            tmpFile2.mkdir();
	        }
	        //消息提示
	        String message = "0";
	       Books book = new Books();
	        try {
	            //使用Apache文件上传组件处理文件上传步骤：
	            //1、创建一个DiskFileItemFactory工厂
	            DiskFileItemFactory factory = new DiskFileItemFactory();
	            //设置工厂的缓冲区的大小，当上传的文件大小超过缓冲区的大小时，就会生成一个临时文件存放到指定的临时目录当中。
	            factory.setSizeThreshold(1024 * 100);//设置缓冲区的大小为100KB，如果不指定，那么缓冲区的大小默认是10KB
	            //设置上传时生成的临时文件的保存目录
	            factory.setRepository(tmpFile);
	            //2、创建一个文件上传解析器
	            ServletFileUpload upload = new ServletFileUpload(factory);
	            //监听文件上传进度
	            upload.setProgressListener(new ProgressListener() {
	                public void update(long pBytesRead, long pContentLength, int arg2) {
	                    System.out.println("文件大小为：" + pContentLength + ",当前已处理：" + pBytesRead);
	                    /**
	                     * 文件大小为：14608,当前已处理：4096
	                     文件大小为：14608,当前已处理：7367
	                     文件大小为：14608,当前已处理：11419
	                     文件大小为：14608,当前已处理：14608
	                     */
	                }
	            });
	            //解决上传文件名的中文乱码
	            upload.setHeaderEncoding("UTF-8");
	            //3、判断提交上来的数据是否是上传表单的数据
	            if (!ServletFileUpload.isMultipartContent(request)) {
	                //按照传统方式获取数据
	            	return ;
	            }

	            //设置上传单个文件的大小的最大值，目前是设置为1024*1024字节，也就是1MB
	            upload.setFileSizeMax(1024 * 1024 * 1024 * 5);
	            //设置上传文件总量的最大值，最大值=同时上传的多个文件的大小的最大值的和，目前设置为5G
	            upload.setSizeMax(1024 * 1024 * 1024 * 5);
	            //4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
	            List<FileItem> list = upload.parseRequest(request);

	            String path1 = null;
	 

	            for (FileItem item : list) {
	                //如果fileitem中封装的是普通输入项的数据
	                if (item.isFormField()) {
	                    String name = item.getFieldName();
	                    //解决普通输入项的数据的中文乱码问题
	                    String value = item.getString("UTF-8");
	                    //value = new String(value.getBytes("iso8859-1"),"UTF-8");
	                    System.out.println(name + "=" + value);
	                    //添加书籍数据	
	                    if ("bnum".equals(name)) {book.setBnum(value);}
	                    if ("bname".equals(name)) {book.setBname(value);}
	                    if ("bauthor".equals(name)) {book.setBauthor(value);}
	                    if ("bpress".equals(name)) {book.setBpress(value);}
	                    if ("bpressdate".equals(name)) {
	                    	SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
	                    	Date parsedate = dateFormat.parse(value);
	                    	book.setBpressdate(parsedate);
	                    	}
	                    if ("borgprice".equals(name)) {book.setBorgprice(Double.valueOf(value));}
	                    if ("bprice".equals(name)) {book.setBprice(Double.valueOf(value));}
	                    if ("bnumber".equals(name)) {book.setBnumber(Integer.valueOf(value));}
	                    if ("bdesc".equals(name)) {book.setBdesc(value);}
	                    if ("cid".equals(name)) {book.setCid(Integer.valueOf(value));}
	                   
	                } else {//如果fileitem中封装的是上传文件
	                    //得到上传的文件名称，
	                    String filename = item.getName();
	                    System.out.println(filename);
	                    if (filename == null || filename.trim().equals("")) {
	                        continue;
	                    }
	                    //注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
	                    //处理获取到的上传文件的文件名的路径部分，只保留文件名部分
	                    filename = filename.substring(filename.lastIndexOf("\\") + 1);
	                    //得到上传文件的扩展名
	                    String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
	                    //如果需要限制上传的文件类型，那么可以通过文件的扩展名来判断上传的文件类型是否合法
	                    System.out.println("上传的文件的扩展名是：" + fileExtName);
	                    //获取item中的上传文件的输入流
	                    InputStream in = item.getInputStream();
	                    //得到文件保存的名称
	                    String saveFilename = makeFileName(filename);
	                    //得到文件的保存目录
	                    // String realSavePath = makePath(saveFilename, savePath);
	                    
	                    //创建一个文件输出流
	                    FileOutputStream out = new FileOutputStream(savePath + "\\" + saveFilename);
	                    //创建一个缓冲区
	                    byte buffer[] = new byte[1024];
	                    //判断输入流中的数据是否已经读完的标识
	                    int len = 0;
	                    //循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
	                    while ((len = in.read(buffer)) > 0) {
	                        //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
	                        out.write(buffer, 0, len);
	                    }
	                    //关闭输入流
	                    in.close();
	                    //关闭输出流
	                    out.close();
	                    //删除处理文件上传时生成的临时文件
	                    //item.delete();
	                    message = "1";
	                    if (path1 == null) {
	                        path1 = "upload/"+saveFilename;
	                        book.setBpicurl(path1);
	                        book.setBflag(1);
	                    }
	                    //上架时间
	                    Timestamp sjtime=new Timestamp(System.currentTimeMillis());  
	                    book.setBtime(sjtime);
	                    
	                }
	            }
	        } catch (FileUploadBase.FileSizeLimitExceededException e) {
	            e.printStackTrace();
	            request.setAttribute("message", "单个文件超出最大值！！！");
	            obj.put("info", "单个文件超出最大值！！！");
               
	            //request.getRequestDispatcher("/upload/message.jsp").forward(request, response);
        		 return;
	        } catch (FileUploadBase.SizeLimitExceededException e) {
	            e.printStackTrace();
	           /* obj.put("info", "上传文件的总的大小超出限制的最大值！！！");
                outSu.print(obj);
        		outSu.flush();
        		outSu.close();*/
        		 return ;
	        } catch (Exception e) {
	            message = "文件上传失败！";
	            obj.put("info",  "文件上传失败！");
	            e.printStackTrace();
	        }
	        //request.setAttribute("message", message);
	       // request.getRequestDispatcher("/upload/message.jsp").forward(request, response);
	        result=booksService.addNewBook(book);
	        System.out.println(message);
	        obj.put("res", result);
            outSu.print(obj);
	    }

    /**
     * @param filename 文件的原始名称
     * @return uuid+"_"+文件的原始名称
     * @Method: makeFileName
     * @Description: 生成上传文件的文件名，文件名以：uuid+"_"+文件的原始名称
     * @Anthor:孤傲苍狼
     */
    private String makeFileName(String filename) {  //2.jpg
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        return UUID.randomUUID().toString() + "_" + filename;
    }

    /**
     * 为防止一个目录下面出现太多文件，要使用hash算法打散存储
     * 未用到
     */
    private String makePath(String filename, String savePath) {
        //得到文件名的hashCode的值，得到的就是filename这个字符串对象在内存中的地址
        int hashcode = filename.hashCode();
        int dir1 = hashcode & 0xf;  //0--15
        int dir2 = (hashcode & 0xf0) >> 4;  //0-15
        //构造新的保存目录
        String dir = savePath + "\\" + dir1 + "\\" + dir2;  //upload\2\3  upload\3\5
        //File既可以代表文件也可以代表目录
        File file = new File(dir);
        //如果目录不存在
        if (!file.exists()) {
            //创建目录
            file.mkdirs();
        }
        return dir;
		
	}

}
